<template>
  <el-form
    ref="ruleFormRef"
    style="max-width: 600px"
    :model="ruleForm"
    status-icon
    :rules="rules"
    label-width="auto"
    class="demo-ruleForm"
  >
    <el-form-item label="原密码" prop="oldPassWord">
      <el-input v-model="ruleForm.oldPassWord" 
			type="password" 
      show-password
			autocomplete="off" />
    </el-form-item>

    <el-form-item label="新密码" prop="newPassword">
      <el-input
        v-model="ruleForm.newPassword"
        type="password"
        autocomplete="off"
        show-password
      />
    </el-form-item>

		<el-form-item label="确认新密码" prop="renewPassword">
      <el-input
        v-model="ruleForm.renewPassword"
        type="password"
        autocomplete="off"
        show-password
      />
    </el-form-item>


    <el-form-item>
      <el-button type="primary" @click="submitForm(ruleFormRef)">
        修改
      </el-button>
      <el-button @click="resetForm(ruleFormRef)">重置</el-button>
    </el-form-item>
  </el-form>
</template>

<script lang="ts" setup>
import { reactive, ref } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { userupdataPs } from '@/Api/api.js'
import { ElMessage } from 'element-plus'


const ruleFormRef = ref<FormInstance>()

//原密码新密码校验规则
const validatePd = (rule:any, value:any, callback:any)=>{

	const passwd = /^(?=.*\d)(?=.*[a-zA-Z])(?=.*[^\da-zA-Z\s]).{6,15}$/
	if (value === '') {	
		callback(new Error('请输入6~15位由数字字母特殊字符组成的密码'))
	} else {
		if (passwd.test(value)) {
			callback()
		}
		callback(new Error('请输入6~15位由数字字母特殊字符组成的密码'))
	}
}

const validatePdEnt = (rule:any, value:any, callback:any)=>{
	if (value === '') {
    callback(new Error('请再次输入密码'))
  } else {
    if (ruleForm.newPassword != '' && value!=ruleForm.newPassword) {
      callback(new Error('两次输入密码不一致'))
    }
    callback()
  }
}

const ruleForm = reactive({
  oldPassWord: '',
  newPassword: '',
	renewPassword:''
})

const rules = reactive<FormRules<typeof ruleForm>>({
  oldPassWord: [{ validator: validatePd, trigger: 'blur' }],
  newPassword: [{ validator: validatePd, trigger: 'blur' }],
  renewPassword: [{ validator: validatePdEnt, trigger: 'blur' }],
})

const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate(async (valid) => {
    if (valid) {
     
			const {data:res} = await userupdataPs(ruleForm)
      ElMessage({
        message:'修改成功',
        type: 'success',
      })

    } else {
      console.log('校验失败')
    }
  })
}

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}
</script>
